/**
 * 文本转语音工具 (Text to Speech)
 * 基于浏览器原生 Web Speech API 封装
 */

// 检查浏览器是否支持语音合成
const isSupported = () => {
  return 'speechSynthesis' in window
}

// 获取所有可用的语音列表
export const getVoices = () => {
  if (!isSupported()) {
    console.warn('[TextToSpeech] 浏览器不支持语音合成')
    return []
  }
  
  try {
    return window.speechSynthesis.getVoices()
  } catch (err) {
    console.error('[TextToSpeech] 获取语音列表失败:', err)
    return []
  }
}

// 根据语言获取可用的语音列表
export const getVoicesByLang = (lang) => {
  const voices = getVoices()
  return voices.filter(voice => voice.lang.includes(lang) || voice.lang === lang)
}

// 当前正在播放的 utterance
let currentUtterance = null

/**
 * 播放文本内容
 * @param {String} text - 要播放的文本内容
 * @param {Object} options - 配置选项
 * @returns {Promise}
 */
export const speakText = (text, options = {}) => {
  if (!text || typeof text !== 'string') {
    return Promise.reject(new Error('文本内容不能为空'))
  }

  if (!isSupported()) {
    console.warn('[TextToSpeech] 浏览器不支持语音合成')
    return Promise.reject(new Error('浏览器不支持语音合成'))
  }

  return new Promise((resolve, reject) => {
    try {
      // 停止之前的播放
      window.speechSynthesis.cancel()
      currentUtterance = null

      // 创建 utterance
      const utterance = new SpeechSynthesisUtterance(text)

      // 设置默认配置
      const config = {
        lang: 'zh-CN',      // 语言
        rate: 1,            // 语速 (0.1 - 10)
        pitch: 1,           // 音调 (0 - 2)
        volume: 1,          // 音量 (0 - 1)
        voice: null,        // 语音名称
        onStart: null,      // 开始播放回调
        onEnd: null,        // 播放结束回调
        onError: null,      // 错误回调
        onPause: null,      // 暂停回调
        onResume: null,     // 继续播放回调
        ...options
      }

      // 设置语音参数
      utterance.lang = config.lang
      utterance.rate = config.rate
      utterance.pitch = config.pitch
      utterance.volume = config.volume

      // 尝试设置指定语音或使用中文语音
      if (config.voice) {
        const voices = getVoices()
        const selectedVoice = voices.find(v => v.name === config.voice)
        if (selectedVoice) {
          utterance.voice = selectedVoice
        }
      } else if (config.lang.includes('zh') || config.lang.includes('CN')) {
        // 自动选择中文语音
        const voices = getVoices()
        const chineseVoice = voices.find(voice => 
          voice.lang.includes('zh') || voice.lang.includes('CN')
        )
        if (chineseVoice) {
          utterance.voice = chineseVoice
        }
      }

      // 绑定事件
      utterance.onstart = () => {
        currentUtterance = utterance
        if (config.onStart) {
          config.onStart()
        }
      }

      utterance.onend = () => {
        currentUtterance = null
        if (config.onEnd) {
          config.onEnd()
        }
        resolve()
      }

      utterance.onerror = (event) => {
        currentUtterance = null
        const error = new Error(event.error || '语音播放失败')
        if (config.onError) {
          config.onError(error)
        }
        reject(error)
      }

      utterance.onpause = () => {
        if (config.onPause) {
          config.onPause()
        }
      }

      utterance.onresume = () => {
        if (config.onResume) {
          config.onResume()
        }
      }

      // 开始播放
      currentUtterance = utterance
      window.speechSynthesis.speak(utterance)
      
      console.log('[TextToSpeech] 开始播放:', text)
    } catch (err) {
      currentUtterance = null
      console.error('[TextToSpeech] 播放失败:', err)
      const error = new Error(err.message || '语音播放失败')
      if (options.onError) {
        options.onError(error)
      }
      reject(error)
    }
  })
}

/**
 * 暂停当前播放
 * @returns {Boolean} 成功返回true，失败返回false
 */
export const pauseSpeech = () => {
  if (!isSupported()) {
    return false
  }

  try {
    if (window.speechSynthesis.speaking && !window.speechSynthesis.paused) {
      window.speechSynthesis.pause()
      return true
    }
    return false
  } catch (err) {
    console.error('[TextToSpeech] 暂停失败:', err)
    return false
  }
}

/**
 * 继续播放
 * @returns {Boolean} 成功返回true，失败返回false
 */
export const resumeSpeech = () => {
  if (!isSupported()) {
    return false
  }

  try {
    if (window.speechSynthesis.speaking && window.speechSynthesis.paused) {
      window.speechSynthesis.resume()
      return true
    }
    return false
  } catch (err) {
    console.error('[TextToSpeech] 继续播放失败:', err)
    return false
  }
}

/**
 * 停止播放
 * @returns {Boolean} 成功返回true，失败返回false
 */
export const stopSpeech = () => {
  if (!isSupported()) {
    return false
  }

  try {
    window.speechSynthesis.cancel()
    currentUtterance = null
    return true
  } catch (err) {
    console.error('[TextToSpeech] 停止播放失败:', err)
    return false
  }
}

/**
 * 检查是否正在播放
 * @returns {Boolean}
 */
export const isSpeaking = () => {
  if (!isSupported()) {
    return false
  }

  try {
    return window.speechSynthesis.speaking && !window.speechSynthesis.paused
  } catch (err) {
    return false
  }
}

// 默认导出所有方法
export default {
  speakText,
  pauseSpeech,
  resumeSpeech,
  stopSpeech,
  isSpeaking,
  getVoices,
  getVoicesByLang
}




